#ifndef CERT_RECOVER_H_
#define CERT_RECOVER_H_

#include <stdint.h>
#include "crypto.h"

#define CRL_SN_LEN		        3		/*certificate serial number 3 bytes*/
#define CRL_NUM_MAX		        50
#define PUBKEY_CERT_KEYLEN		200

/* Certificate recover structure */
typedef struct {
	uint8_t * cert;
	uint32_t  certlen;
	uint8_t * pk_remainder;
	uint32_t  pk_remainder_len;
}cert_recv_t;

/* certificate recover */
#define CERT_HEAD_PK			0xCA
#define CERT_HEAD_CRL 			0xCB
#define CERT_TAIL		        0xCF
#define CERT_HASHAL         	        0x02		/*hash algorithm*/
#define CERT_PKAL           	        0x01		/*pk algorithm*/

/* public key certificate */
typedef struct {
        uint8_t head;                   		/*0xCA*/
        uint8_t expire_date[2];         		/*MMYY, e.g.:0x0213 -> 2013-02*/
        uint8_t key_usage;              		/*Hex Value 0x01: PED public Key
                                                 	        0x02: Host Public Key(HSM/KLD)*/
        uint8_t cert_sn[3];             		/*certificate unique binary number*/
        uint8_t hash_algo;              		/*only 0x02(SHA256) acceptable*/
        uint8_t pk_algo;                		/*Only 0x01(PKCS#1 V1.5) acceptable*/
        uint8_t pk_left[PUBKEY_CERT_KEYLEN];            /*the leftmost 200 bytes of public key*/
        uint8_t hash[32];               		/*hash result of the value from 'expire_data' to 'pk_left'*/
        uint8_t tail;                  		        /*0xCF*/
	uint8_t recv[14];
}pk_cert_t;

/* CRL certificate */
typedef struct {
        uint8_t head;                   		/*0xCA*/
        uint8_t hash_algo;              		/*only 0x02(SHA256) acceptable*/
        uint8_t pk_algo;                		/*Only 0x01(PKCS#1 V1.5) acceptable*/
        uint8_t num;					/* the num of CRL*/
        uint8_t crl[50][3];           		        /*the leftmost 200 bytes of public key*/
        uint8_t hash[32];               		/*hash result of the value from 'expire_data' to 'pk_left'*/
        uint8_t trail;                  		/*0xCF*/
}crl_cert_t;


#define CERT_ERR_PARA           	-1      /*Parameter error*/
#define CERT_ERR_HEAD           	-2      /*header error*/
#define CERT_ERR_TAIL           	-3      /*tail error*/
#define CERT_ERR_HASHAL          	-4      /*hash algorithm error*/
#define CERT_ERR_PKAL           	-5      /*public algorithm error*/
#define CERT_ERR_HASH           	-6      /*hash check error*/
#define CERT_ERR_EXPIRE           	-7      /*certificate expired*/
#define CERT_ERR_CRL                   -8      /*certificate in revocation List*/
#define CERT_ERR_LEN                   -9      /*certificate len error*/
#define CERT_ERR_RSA                   -10     /*RSA crypto error*/

int pk_cert_recover( cert_recv_t *certin, uint8_t *output,
		uint32_t *outlen, R_RSA_PUBLIC_KEY *dekey);

int crl_cert_recover( uint8_t *cert, uint32_t certlen, uint8_t *output,
		uint32_t * outlen, R_RSA_PUBLIC_KEY *key);

int find_in_crl( uint8_t *sn );


#endif /*CERT_RECOVER_H_*/
